package br.com.requisicao.compra.pdf;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import javax.servlet.http.HttpServletResponse;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;

public class ExportarPdf {

	public final static String CAMINHO_PDF = "C:\\requisicaocompraconfig\\pdf\\PedidoCotacao";
	public final static String FORMATO_PDF = ".pdf";

	// responsavel por gerar o pdf do pedido de cotacao
	public static void gerarPdf(String template, String tituloPdf)
			throws IOException, DocumentException {

		// criacao do documento
		Document document = new Document();
		HTMLWorker htmlWorker = new HTMLWorker(document);
		PdfWriter pdfWriter = PdfWriter.getInstance(document,
				new FileOutputStream(CAMINHO_PDF.concat(FORMATO_PDF)));

		HttpServletResponse response = FacesUtils.getResponse();

		try {

			document.open();
			htmlWorker.startDocument();

			htmlWorker.parse(new StringReader(template));

			htmlWorker.endDocument();
			htmlWorker.close();

			FileInputStream baos = new FileInputStream(
					CAMINHO_PDF.concat(FORMATO_PDF));
			document.close();

			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition", "attachment; filename=" + tituloPdf + FORMATO_PDF);

			OutputStream os = response.getOutputStream();

			byte buffer[] = new byte[8192];
			int bytesRead;

			while ((bytesRead = baos.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}

			os.flush();
			os.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void gerarPdfEnvioEmail(String template, String tituloPdf, String caminhoPdf)
			throws IOException, DocumentException {

		// criacao do documento
		Document document = new Document();
		HTMLWorker htmlWorker = new HTMLWorker(document);

		PdfWriter pdfWriter = PdfWriter.getInstance(document,
				new FileOutputStream(caminhoPdf.concat(FORMATO_PDF)));

		try {

			document.open();
			htmlWorker.startDocument();

			htmlWorker.parse(new StringReader(template));

			htmlWorker.endDocument();
			htmlWorker.close();

			document.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
